package com.bg.sparkproject.pattern.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Auther: zhengshunzhi
 * @Date: 2019/1/4 14:27
 * @Description: Cglib子类代理工厂
 */
public class CglibProxyFactory implements MethodInterceptor {
    //维护目标对象
    private Object target;

    public CglibProxyFactory(Object target) {
        this.target = target;
    }

    //给目标对象创建一个代理对象
    public <T> T getProxyInstance() {
        //1.工具类
        Enhancer en = new Enhancer();
        //2.设置父类
        en.setSuperclass(target.getClass());
        //3.设置回调函数
        en.setCallback(this);
        //4.创建子类(代理对象)
        return (T) en.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("买房前准备");
        //执行目标对象的方法
        Object result = method.invoke(target, args);
        System.out.println("买房后装修");
        return result;
    }

    public static void main(String[] args) {
        Hosue target = new Hosue();
        System.out.println(target.getClass());
        Hosue hosue = (Hosue) new CglibProxyFactory(target).getProxyInstance();
        System.out.println(hosue.getClass());
        hosue.buyVilla();
    }
}
